<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html><head><title>Programming in Lua : 16.2</title>
<link rel="stylesheet" type="text/css" href="pil.css">
</head>
<body>
<p class="warning">
<A HREF="contents.html"><IMG TITLE="Programming in Lua (first edition)" SRC="capa.jpg" ALT="" ALIGN="left"></A>This first edition was written for Lua 5.0. While still largely relevant for later versions, there are some differences.<BR>The third edition targets Lua 5.2 and is available at <A HREF="http://www.amazon.com/exec/obidos/ASIN/859037985X/theprogrammil3-20">Amazon</A> and other bookstores.<BR>By buying the book, you also help to <A HREF="../donations.html">support the Lua project</A>.
</p>
<table width="100%" class="nav">
<tr>
<td width="10%" align="left"><a href="16.1.html"><img border="0" src="left.png" alt="Previous"></a></td>
<td width="80%" align="center"><a href="contents.html"><font face="Helvetica,Arial,sanserif">
<font color="gray">Programming in </font><font color="blue"> Lua</font>
</font></a></td>
<td width="10%" align="right"><a href="16.3.html"><img border="0" src="right.png" alt="Next"></a></td>
</tr>
<tr>
<td width="10%" align="left"></td>
<td width="80%" align="center"><a href="contents.html#P2">Part II. Tables and Objects</a>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<a href="contents.html#16">Chapter 16. Object-Oriented Programming</a></td>
<td width="10%" align="right"></td></tr>
</table>
<hr/>
<p><h2>16.2 &ndash; Inheritance</h2>

<p>Because classes are objects,
they can get methods from other classes, too.
That makes inheritance
(in the usual object-oriented meaning) quite easy to
implement in Lua.

<p>Let us assume we have a base class like <code>Account</code>:
<pre>
    Account = {balance = 0}
    
    function Account:new (o)
      o = o or {}
      setmetatable(o, self)
      self.__index = self
      return o
    end
    
    function Account:deposit (v)
      self.balance = self.balance + v
    end
    
    function Account:withdraw (v)
      if v > self.balance then error"insufficient funds" end
      self.balance = self.balance - v
    end
</pre>

<p>From that class, we want to derive a subclass <code>SpecialAccount</code>,
which allows the customer to withdraw more than his balance.
We start with an empty class
that simply inherits all its operations from its base class:
<pre>
    SpecialAccount = Account:new()
</pre>
Up to now, <code>SpecialAccount</code> is just an instance of <code>Account</code>.
The nice thing happens now:
<pre>
    s = SpecialAccount:new{limit=1000.00}
</pre>
<code>SpecialAccount</code> inherits <code>new</code> from <code>Account</code>
like any other method.
This time, however, when <code>new</code> executes,
the <code>self</code> parameter will refer to <code>SpecialAccount</code>.
Therefore, the metatable of <code>s</code> will be <code>SpecialAccount</code>,
whose value at index <code>__index</code> is also <code>SpecialAccount</code>.
So, <code>s</code> inherits from <code>SpecialAccount</code>,
which inherits from <code>Account</code>.
When we evaluate
<pre>
    s:deposit(100.00)
</pre>
Lua cannot find a <code>deposit</code> field in <code>s</code>,
so it looks into <code>SpecialAccount</code>;
it cannot find a <code>deposit</code> field there, too,
so it looks into <code>Account</code>
and there it finds the original implementation for a deposit.

<p>What makes a <code>SpecialAccount</code> special is that it can redefine
any method inherited from its superclass.
All we have to do is to write the new method:
<pre>
    function SpecialAccount:withdraw (v)
      if v - self.balance >= self:getLimit() then
        error"insufficient funds"
      end
      self.balance = self.balance - v
    end
    
    function SpecialAccount:getLimit ()
      return self.limit or 0
    end
</pre>
Now, when we call <code>s:withdraw(200.00)</code>,
Lua does not go to <code>Account</code>,
because it finds the new <code>withdraw</code>
method in <code>SpecialAccount</code> first.
Because <code>s.limit</code> is 1000.00
(remember that we set this field when we created <code>s</code>),
the program does the withdrawal,
leaving <code>s</code> with a negative balance.

<p>An interesting aspect of OO in Lua is that you do not
need to create a new class to specify a new behavior.
If only a single object needs a specific behavior,
you can implement that directly in the object.
For instance, if the account <code>s</code> represents some
special client whose limit is always 10% of her balance,
you can modify only this single account:
<pre>
    function s:getLimit ()
      return self.balance * 0.10
    end
</pre>
After that declaration, the call <code>s:withdraw(200.00)</code>
runs the <code>withdraw</code> method from <code>SpecialAccount</code>,
but when that method calls <code>self:getLimit</code>,
it is this last definition that it invokes.

<hr/>
<table width="100%" class="nav">
<tr valign="top">
<td width="90%" align="left">
<small>
  Copyright &copy; 2003&ndash;2004 Roberto Ierusalimschy.  All rights reserved.
</small>
</td>
<td width="10%" align="right"><a href="16.3.html"><img border="0" src="right.png" alt="Next"></a></td>
</tr>
</table>


</body></html>

